/**
 * 数据统计页面
 * 展示详细的博客数据统计信息，包括文章、用户、评论等数据
 */

'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { 
  BarChart3, 
  Users, 
  FileText, 
  MessageSquare, 
  Eye, 
  Calendar,
  TrendingUp,
  Clock
} from 'lucide-react';

// 统计数据接口
interface StatsData {
  overview: {
    totalPosts: number;
    publishedPosts: number;
    draftPosts: number;
    totalComments: number;
    pendingComments: number;
    totalUsers: number;
    totalViews: number;
  };
  recentPosts: Array<{
    id: string;
    title: string;
    status: string;
    createdAt: string;
    author: { name: string };
    tags: Array<{ name: string }>;
  }>;
  popularTags: Array<{
    name: string;
    count: number;
  }>;
}

/**
 * 数据统计页面组件
 * @returns JSX 元素
 */
export default function StatsPage() {
  const [stats, setStats] = useState<StatsData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchStats = async () => {
      try {
        // 获取认证token
        const token = document.cookie
          .split('; ')
          .find(row => row.startsWith('auth-token='))
          ?.split('=')[1];

        if (!token) {
          console.error('未找到认证token');
          setLoading(false);
          return;
        }

        // 获取统计数据
        const response = await fetch('/api/stats', {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });

        if (response.ok) {
          const data = await response.json();
          setStats(data);
        } else {
          console.error('获取统计数据失败');
        }
      } catch (error) {
        console.error('获取统计数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchStats();
  }, []);

  /**
   * 格式化日期
   * @param dateString ISO 日期字符串
   * @returns 格式化的中文日期字符串
   */
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <div className="container mx-auto px-4 py-8">
          <div className="flex items-center justify-center h-64">
            <div className="text-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
              <p className="text-muted-foreground">加载统计数据中...</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (!stats) {
    return (
      <div className="min-h-screen bg-background">
        <div className="container mx-auto px-4 py-8">
          <div className="text-center">
            <h1 className="text-2xl font-bold mb-4">数据统计</h1>
            <p className="text-muted-foreground">无法加载统计数据</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="container mx-auto px-4 py-8">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold mb-2">数据统计</h1>
          <p className="text-muted-foreground">查看博客的详细数据统计信息</p>
        </div>

        {/* 概览统计卡片 */}
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4 mb-8">
          {/* 总文章数 */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">总文章数</CardTitle>
              <FileText className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.overview.totalPosts}</div>
              <p className="text-xs text-muted-foreground">
                已发布 {stats.overview.publishedPosts} 篇，草稿 {stats.overview.draftPosts} 篇
              </p>
            </CardContent>
          </Card>

          {/* 总浏览量 */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">总浏览量</CardTitle>
              <Eye className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.overview.totalViews.toLocaleString()}</div>
              <p className="text-xs text-muted-foreground">
                所有文章的总浏览量
              </p>
            </CardContent>
          </Card>

          {/* 总评论数 */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">总评论数</CardTitle>
              <MessageSquare className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.overview.totalComments}</div>
              <p className="text-xs text-muted-foreground">
                待审核 {stats.overview.pendingComments} 条
              </p>
            </CardContent>
          </Card>

          {/* 总用户数 */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">总用户数</CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.overview.totalUsers}</div>
              <p className="text-xs text-muted-foreground">
                注册用户总数
              </p>
            </CardContent>
          </Card>
        </div>

        <div className="grid gap-6 lg:grid-cols-2">
          {/* 最近文章 */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Clock className="h-5 w-5" />
                最近文章
              </CardTitle>
              <CardDescription>最近创建或更新的文章</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {stats.recentPosts.length === 0 ? (
                  <p className="text-muted-foreground text-center py-4">暂无文章</p>
                ) : (
                  stats.recentPosts.map((post) => (
                    <div key={post.id} className="flex items-center justify-between p-3 border rounded-lg">
                      <div className="flex-1">
                        <h4 className="font-medium text-sm mb-1">{post.title}</h4>
                        <div className="flex items-center gap-2 text-xs text-muted-foreground">
                          <span>{post.author.name}</span>
                          <span>•</span>
                          <span>{formatDate(post.createdAt)}</span>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <Badge variant={post.status === 'PUBLISHED' ? 'default' : 'secondary'}>
                          {post.status === 'PUBLISHED' ? '已发布' : '草稿'}
                        </Badge>
                      </div>
                    </div>
                  ))
                )}
              </div>
            </CardContent>
          </Card>

          {/* 热门标签 */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <TrendingUp className="h-5 w-5" />
                热门标签
              </CardTitle>
              <CardDescription>使用频率最高的标签</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {stats.popularTags.length === 0 ? (
                  <p className="text-muted-foreground text-center py-4">暂无标签</p>
                ) : (
                  stats.popularTags.map((tag, index) => (
                    <div key={tag.name} className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <span className="text-sm font-medium text-muted-foreground w-6">
                          #{index + 1}
                        </span>
                        <Badge variant="outline">{tag.name}</Badge>
                      </div>
                      <span className="text-sm text-muted-foreground">
                        {tag.count} 篇文章
                      </span>
                    </div>
                  ))
                )}
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
